package com.kk.xhr.web.security;

import com.kk.xhr.common.pojo.AuthUser;
import com.kk.xhr.common.pojo.UserStatusEnum;
import com.kk.xhr.model.entity.Role;
import com.kk.xhr.model.entity.User;
import com.kk.xhr.model.service.IPermissionService;
import com.kk.xhr.model.service.IRoleService;
import com.kk.xhr.model.service.IUserService;
import com.kk.xhr.web.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * MyAuthorizingRealm
 *
 * @author kkmystery
 * @version 1.0 2021/3/9
 * @since 1.0.0
 */
public class MyAuthorizingRealm extends AuthorizingRealm {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyAuthorizingRealm.class);

    @Autowired
    @Lazy
    private IUserService userService;

    @Autowired
    @Lazy
    private IRoleService roleService;

    @Autowired
    @Lazy
    private IPermissionService permissionService;

    {
        this.setCredentialsMatcher(new JwtCredentialsMatcher());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 获取角色与权限
     * doGetAuthorizationInfo执行时机有三个，如下：
     * 1、subject.hasRole(“admin”) 或 subject.isPermitted(“admin”)：自己去调用这个是否有什么角色或者是否有什么权限的时候；
     * 2、@RequiresRoles("admin") ：在方法上加注解的时候；
     * 3、@shiro.hasPermission name = "admin"/@shiro.hasPermission："dustin:test"在页面上加shiro标签的时候，即进这个页面的时候扫描到有这个标签的时候。
     *
     * @param principalCollection 身份
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if (null == principalCollection) {
            throw new AuthorizationException("PrincipalCollection is null.");
        }
        AuthUser authUser = (AuthUser) getAvailablePrincipal(principalCollection);
        LOGGER.info("授权信息：{}", authUser);
        // 用户授权匹配
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(authUser.getRoles());
        info.setStringPermissions(authUser.getPermissions());
        return info;
    }

    /**
     * 登录信息验证
     * <p>
     * 1.doGetAuthenticationInfo执行时机如下
     * 当调用Subject currentUser = SecurityUtils.getSubject();
     * currentUser.login(token);
     *
     * @param authenticationToken 认证token
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        final JwtToken jwtToken = (JwtToken) authenticationToken;
        String token = (String) jwtToken.getPrincipal();
        LOGGER.info("Token={}", token);
        Optional<String> claimOptional = JwtUtil.getClaim(token);
        if (!claimOptional.isPresent()) {
            throw new AuthenticationException("Invalid token " + token);
        }
        final String claim = claimOptional.get();
        final Long claimUserId = Long.parseLong(claim);
        // 优先使用缓存查询密钥，查询活跃的用户
        User user = userService.queryUser(claimUserId);
        if (null == user || UserStatusEnum.ACTIVE.getValue() != user.getStatus()) {
            throw new AuthenticationException("User " + claim + " not active.");
        }
        AuthUser authUser = new AuthUser();
        Long userId = user.getId();
        Set<String> roles = roleService.queryRolesByUserId(userId).stream().map(Role::getName).collect(Collectors.toSet());
        Set<String> permissions = permissionService.queryPermissionsByUserId(userId);
        authUser.setUserId(userId);
        authUser.setUsername(user.getName());
        authUser.setRoles(roles);
        authUser.setPermissions(permissions);
        return new SimpleAuthenticationInfo(authUser, new JwtToken(token), claim);
    }
}
